package logs

import (
	"fmt"
	"runtime"
	"gitee.com/winnie_gss/MessageBox/logs/vender/gopkg.in/ini.v1"
	"os"
	"time"
)

type LogConfig struct {
	LogLevel int
}

var logconfig LogConfig
var folderPath string
var filePath string

func InitLog() {

	pwd, _ := os.Getwd()
	pwd += "\\.."
	file, err := ini.Load(pwd + "\\config.ini")
	SimplePanic(err)

	file.BlockMode = false
	err = file.Section("log").MapTo(&logconfig)
	SimplePanic(err)

	folderPath = pwd + "\\runtime\\" + time.Now().Format("200601")
	filePath = folderPath + "\\" + time.Now().Format("02.log")

	if _, err := os.Stat(folderPath); os.IsNotExist(err) {
		os.Mkdir(folderPath, 0777)
	}
}

func DebugLog(str string) {
	if logconfig.LogLevel > 1 {
		return
	}
	WriteLog(str, "Debug")
}

func InfoLog(str string) {
	if logconfig.LogLevel > 2 {
		return
	}
	WriteLog(str, "Info")
}

func ErrorLog(err error) {
	if err != nil {
		WriteLog(err, "Error")
	}
}

func WriteLog(str interface{}, level string) {
	_, files, line, _ := runtime.Caller(2)

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0777)
	SimplePanic(err)

	content := fmt.Sprintf("[ %s ] %s : %d\r\n[ %s ] %s\r\n---------------------------------------------------------------\r\n", time.Now().Format("2006-01-02 15:04:05"), files, line, level, str)
	file.Write([]byte(content))
}

func SimplePanic(err error) {
	if err != nil {
		_, file, line, _ := runtime.Caller(1)
		fmt.Println("----------------------------------------")
		fmt.Println(file, line)
		fmt.Println(err)
		fmt.Println("----------------------------------------")
		runtime.Goexit()
	}
}
